package com.zsw.security.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author 张士伟
 * @date 2020/7/25 18:02
 **/
/*
 * 自定义配置安全框架
 * */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*授权*/
        /*首页可以所有人访问*/
        /*功能页对应相对应的权限才能访问*/
        http.authorizeRequests().antMatchers("/").permitAll()
                /* .antMatchers("/**").hasRole("vip1")*/
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        /*
         *没有权限自动跳转到登录页面
         * 定制登陆页
         * */

        http.formLogin().loginPage("/toLogin").usernameParameter("username").
                passwordParameter("password").loginProcessingUrl("/login");
        /*关闭防止网站的csrf的网站攻击*/
        http.csrf().disable();
        /*开启记住我功能*/
        http.rememberMe().rememberMeParameter("remember");
        /*注销*/
        http.logout();
    }


    /*认证规则*/
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zsw").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("1234")).roles("vip3", "vip1");
    }
}